# -*- coding: utf-8 -*-
# @Time    : 2018/2/5 12:02
# @Author  : Soft
# @File    : service.py
# @Desc    : 用户service层
from module.models import Student, db, Page, Record, Class, Work, z_study_record
from module.TimeUtils import *
from config import Check as CheckUp, WorkUp
from peewee import *
import logging

log = logging.getLogger('Student Service LOG')


class StuService:
    def __init__(self):
        pass

    @staticmethod
    def login(u_id='', pass_wd=''):
        pass_wd = pass_wd
        result = Student.select().where(Student.stu_id == u_id, Student.stu_pass == pass_wd)
        if len(result) >= 1:
            return True, result[0]
        return False, None

    @staticmethod
    @db.atomic()
    def add(**stu):
        reg_time = get_time()
        sp = stu.get('stu_pass')
        stu['stu_pass'] = sp
        return Student.insert(stu_reg_time=reg_time, **stu).execute()

    @staticmethod
    @db.atomic()
    def remove(uid=0):
        try:
            Record.delete().where(Record.stu == uid).execute()
            Work.delete().where(Work.stu == uid).execute()
            z_study_record.delete().where(z_study_record.stu == uid).execute()
            return Student.delete_by_id(uid)
        except BaseException as e:
            log.debug("删除课程(id: %s)的记录失败--> %s" % (uid, e))

    @staticmethod
    def change(stu_id='', **stu):
        if stu.get('stu_pass') is not None:
            sp = stu.get('stu_pass')
            stu['stu_pass'] = sp
        try:
            with db.atomic():
                Student.update(**stu).where(Student.stu_id == stu_id).execute()
                return True
        except BaseException as e:
            print(e)
            return False

    @staticmethod
    def stu_count(year=None):
        try:
            if year:
                return Student.select().where(Student.stu_reg_time.startswith(year)).count()
            return Student.select().count()
        except BaseException as e:
            log.debug('统计学生总数失败--> %s' % e)
            return 0

    @staticmethod
    def query_stu_id(stu_id=''):
        """
        根据账号获取用户
        :param stu_id: 用户账号
        """
        students = Student.select().where(Student.stu_id == stu_id)
        if len(students):
            return students[0].to_dict()
        return None

    @staticmethod
    def find_by_id(uid=0):
        """
        通过id获取用户
        :return:
        """
        try:
            return Student.get_by_id(int(uid))
        except BaseException as e:
            log.debug('id %s 获取用户失败 --> %s' % (uid, e))
            return None

    @staticmethod
    def query_name(real_name=''):
        """
        通过姓名获取用户
        :return:
        """
        sql = 'select * from student WHERE stu_name LIKE %s'
        stus = StuService.query_sql(sql, "%" + real_name.strip() + "%")
        if len(stus) > 0:
            for stu in stus:
                year = str(stu.get('stu_reg_time'))[:4]
                class_num = Class.select().where(Class.k_time.startswith(year)).count()
                record_num = Record.select().where(Record.rd_time.startswith(year),
                                                   Record.stu == stu.get('id'),
                                                   Record.rd_status.in_([CheckUp.CQ, CheckUp.CD])).count()
                work_num = Work.select().where(Work.work_uptime.startswith(year),
                                               Work.stu == stu.get('id'),
                                               Work.work_status.in_([WorkUp.YJ, WorkUp.YQ])).count()
                stu.setdefault('record_num', record_num)
                stu.setdefault('work_num', work_num)
                stu.setdefault('class_num', class_num)
        return stus

    @staticmethod
    def pages(page=1, size=12, year=2018):
        class_num = Class.select().where(Class.k_time.startswith(year), Class.k_status!=Clazz_ST.WKS).count()
        data = []
        results = Student.select().where(Student.stu_reg_time.startswith(year)). \
            order_by(Student.id.desc()).paginate(page, size)
        for result in results:
            stu = dict(result.to_dict())
            record_num = Record.select().where(Record.rd_time.startswith(year),
                                               Record.stu == stu.get('id'),
                                               Record.rd_status.in_([CheckUp.CQ, CheckUp.CD])).count()
            work_num = Work.select().where(Work.work_uptime.startswith(year),
                                           Work.stu == stu.get('id'),
                                           Work.work_status.in_([WorkUp.YJ, WorkUp.YQ])).count()
            stu.setdefault('record_num', record_num)
            stu.setdefault('work_num', work_num)
            stu.setdefault('class_num', class_num)
            data.append(stu)
        Page.result = data
        Page.page = page
        Page.limit = size
        Page.total = Student.select().where(Student.stu_reg_time.startswith(year)).count()
        return Page.to_dict()

    @staticmethod
    def query_sql(sql, *param):
        s = []
        for t in Student.raw(sql, *param):
            s.append(t.to_dict())
        return s

    @staticmethod
    def by_year(year='2018'):
        stus = StuService.query_sql('select id, stu_id, stu_name, stu_class, stu_tel from student WHERE substring(stu_reg_time, 1, 4) in (%s)',
                                    year)
        if len(stus):
            stus.insert(0, {'stu_name': u'全部学员', 'id': 0})
        else:
            stus.insert(0, {'stu_name': u'暂无学员', 'id': 0})
        return stus

    @staticmethod
    def get_year_group():  # 按照注册时间分组
        return StuService.query_sql('select substring(stu_reg_time, 1, 4) as stu_reg_time from student '
                                    'group by substring(stu_reg_time, 1, 4)')

    @staticmethod
    def get_name_pass(uid):  # 提供给验证登录用 返回账号和密码
        try:
            student = Student.get_by_id(uid)
            return student.stu_id, student.stu_pass
        except DoesNotExist as e:
            log.debug('获取用户失败--> %s' % e)
            return ' ', ' '
